package cn.somkit.fmt.config;

import cn.metona.mq.MQToolkit;
import cn.metona.mq.consumer.MessageConsumer;
import cn.metona.mq.utils.MonitorUtils;
import cn.somkit.fmt.socket.SocketManage;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

@Component
public class LogMonitorConfig {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String Queue_Name = "log-monitor";

    private static final String Consumer_Id = "log-monitor-consumer";

    @PostConstruct
    public void run(){
        //创建日志监控队列
        MQToolkit.createQueue(Queue_Name, Boolean.FALSE);
        //创建日志监控消费者
        MessageConsumer consumer = MQToolkit.createConsumer(Consumer_Id, Queue_Name, message -> {
            List<WebSocketSession> list = SocketManage.all();
            if(list != null && !list.isEmpty()){
                list.forEach(session -> {
                    if(session.isOpen()){
                        try {
                            session.sendMessage(new TextMessage(message.body()));
                        } catch (IOException e) {
                            logger.error("发送消息失败：", e);
                        }
                    }
                });
            }
        });
        //启动消费者
        consumer.start();
        // 显示队列统计
        MonitorUtils.printQueueStats(Queue_Name);
    }
}
